
# ---内置库---
import os
import sys
import time
import datetime
import json

# ---第三方库---
from colorama import init, Fore, Back, Style
from experta import Fact, KnowledgeEngine, Rule, MATCH, AS, W
import pyperclip

# ---自研库---
from lib.mytools import getNowTime
from lib.mytools import basicClass, readJsonFile, writeJsonFile
from core.Operator_DB import Sqlite_Operator
from lib.Helper_Api_Json_combine import Api_Json_Maker


class Json_maker(Api_Json_Maker):
    def __init__(self):
        super().__init__()
        self.instanceName = 'Api_Json_maker->'
        self.db_source = Sqlite_Operator()  # 用于读取
        self.db_source.connect(
            r'data\data.db')
        self.level_0_table = 't_level_0'
        self.level_1_table = 't_level_1'
        self.level_2_table = 't_level_2'

    def read_config(self):
        self._cfg_path = r'cfg\Setting.json'
        cfg_dict = readJsonFile(self._cfg_path)
        self._db_path = cfg_dict['db_path']

    def call_parnter(self):
        self.db_source = Sqlite_Operator()

    def ready_to_run(self):
        self.db_source.connect(self._db_path)
        self.level_0_table = 't_level_0'
        self.level_1_table = 't_level_1'
        self.level_2_table = 't_level_2'

    def iqc_detail_L0(self, **kwargs):
        level0 = {
            "msgId": kwargs.get('msgId', "296889EFD44E1EDFAAD9897AA81C6F40"),
            "resultList": kwargs.get("resultList", []),  # L1填充入口
            "sourceRfc": kwargs.get("sourceRfc", "ZRFC_QM_003")
        }
        return level0

    def iqc_detail_L1(self, **kwargs):
        level_1 = {
            "checkNumber": kwargs.get("checkNumber", "4800.000"),
            "decisionResults": kwargs.get("decisionResults", "合格"),
            "detailReqList": kwargs.get("detailReqList", []),  # L2填充入口
            "endDate": kwargs.get("endDate", "2024-11-28 00:00:00"),
            # 1000 是厦门IQC, 2200是重庆IQC
            "factory": kwargs.get("factory", "1000"),
            "finalDecisionId": kwargs.get("finalDecisionId", "001"),
        }
        return level_1

    def iqc_detail_L2(self, **kwargs):
        level_2 = {
            "individualDecision": kwargs.get("individualDecision", "已接受"),
            "inspectionItemCode": kwargs.get("inspectionItemCode", "HL000892"),
            "inspectionItems": kwargs.get("inspectionItems", "铝壳总长|自动二次元影像测量仪|173.6±0.15mm"),
            "inspectionLot": kwargs.get("inspectionLot", "10000139185"),
            "meanValue": kwargs.get("meanValue", "173.5600"),
        }
        return level_2

    def get_json_Combine(self, bill_iid) -> dict:  # 组合json----
        """将三层的字典组合成所需的json

        Args:
            bill_iid (any): 变化因子, 用于变换不同的json

        Returns:
            dict: 生成的字典
        """

        # new layer!读取数据,填充该级别数据---------
        level_0 = self.iqc_detail_L0()

        # new layer!读取数据,填充该级别数据---------
        query_sql_1 = f'SELECT *  FROM 	inspection_bill ib WHERE iid="{bill_iid}"'
        result_l1 = self.db_source.execute_sql(query_sql_1)
        for item in result_l1:
            input_dict1 = {
                "checkNumber": item["checkNumber"],
                "decisionResults": item["decisionResults"],
                # "detailReqList": item["detailReqList"], []),  # L2填充入口
                "endDate": item["endDate"],
                "factory": item["factory"],
                "finalDecisionId": item["finalDecisionId"],
                "inspectionDate": item["inspectionDate"],
                "inspectionLot": item["inspectionLot"],
                "materialName": item["materialName"],
                "materialNumber": item["materialNumber"],
                "purchaseOrder": item["purchaseOrder"],
                "purchaseOrderId": 10,
                "returnNumber": item["returnNumber"],
                "sourceDocuments": item["sourceDocuments"],
                "startDate": item["startDate"],
                "supplier": item["supplier"],
                "supplierLot": item["supplierLot"],
            }
        level_1 = self.iqc_detail_L1(**input_dict1)

        # new layer!读取数据,填充该级别数据-----------
        level_2 = []
        inspection_items_result = self.db_source.execute_sql(
            'select * from inspection_item where material_type="铝壳"')
        for item in inspection_items_result:
            target_value = float(item['target_value'])

            input_dict2 = {
                "inspectionItemCode": item["inspection_item_id"],
                "inspectionItems": item["inspection_item_name"],
                "testResult1": self.random_fluctuation_normal(target_value, 0.2),
                "testResult1": self.random_fluctuation_normal(target_value, 0.2),
                "testResult2": self.random_fluctuation_normal(target_value, 0.2),
                "testResult3": self.random_fluctuation_normal(target_value, 0.2),
                "testResult4": self.random_fluctuation_normal(target_value, 0.2),
                "testResult5": self.random_fluctuation_normal(target_value, 0.2),
            }

            level_2.append(self.iqc_detail_L2(**input_dict2))
        # --开始组装--
        level_0['resultList'].append(level_1)
        level_1['detailReqList'] = level_2
        return level_0


if __name__ == '__main__':
    Jesus = Json_maker()
    Jesus.get_json_Combine(1)
    pass
